package com.itheima.filter;

import com.itheima.commons.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Tang
 * @date 2023/1/6
 */
//value等价于这个urlPattens /*代表拦截所有请求
@WebFilter("/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    //定义一组直接放行的路径
    String[] paths = {
            "/employee/login",
            "/employee/logout",
            "/backend/page/login/login.html",
            "/front/page/login.html",
            "/**/api/**",
            "/**/images/**",
            "/**/js/**",
            "/**/plugins/**",
            "/**/styles/**",
            "/**/*.ico",
            "/user/sendMsg",
            "/user/login"
    };

    //路径匹配器 AntPathMatcher
    AntPathMatcher matcher = new AntPathMatcher();

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        log.info("LoginCheckFilter 线程id: {}",Thread.currentThread().getId());
        //0. 强转对象
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        //1、获取本次请求的URI
        String uri = request.getRequestURI();
        log.info("uri: {}", uri);

        //2、判断本次请求是否需要处理
        //3、如果不需要处理，则直接放行
        for (String path : paths) {
            boolean flag = matcher.match(path, uri);
            if (flag) {
                chain.doFilter(req, resp);
                return;  //直接return，不让继续执行下面的逻辑
            }
        }
        /*if (uri.contains("/login") || uri.contains("/logout") || uri.contains("/api")
                || uri.contains("/images")) {
            chain.doFilter(req, resp);
            return;  //直接return，不让继续执行下面的逻辑
        }*/
        //4、判断登录状态，如果已登录，则直接放行
        Object employeeId = request.getSession().getAttribute("employeeId");
        if (employeeId != null) {
            //设置员工id到threadLocal中
            BaseContext.setCurrentId((Long) employeeId);
            chain.doFilter(req, resp);  //放行
            return;  //直接return，不让继续执行下面的逻辑
        }

        //4、判断登录状态，如果已登录，则直接放行
        Object userId = request.getSession().getAttribute("userId");
        if (userId != null) {
            //设置用户id到threadLocal中
            BaseContext.setCurrentId((Long) userId);
            chain.doFilter(req, resp);  //放行
            return;  //直接return，不让继续执行下面的逻辑
        }


        //5.1、如果未登录则返回未登录结果, 直接返回到登录页面
        if (uri.contains("/front")) {
            response.sendRedirect("/front/page/login.html");
        }

        //5.1、如果未登录则返回未登录结果, 直接返回到登录页面
        if (uri.contains("/backend")) {
            response.sendRedirect("/backend/page/login/login.html");
        }
    }

}
